/*
消息界面路由容器组件
 */
import React, { Component } from "react";
import { connect } from "react-redux";
import { Comment, Avatar } from "antd";
import { List, Badge } from "antd-mobile";
import { getUser } from "../../redux/actions";

const Item = List.Item;

function getLastMsgs(chatMsgs, userid) {
  const lastMsgObjs = {};
  chatMsgs.forEach((msg) => {
    if (msg.to === userid && !msg.read) {
      msg.unReadCount = 1;
    } else {
      msg.unReadCount = 0;
    }

    const chatId = msg.chat_id;
    let lastMsg = lastMsgObjs[chatId];
    if (!lastMsg) {
      lastMsgObjs[chatId] = msg;
    } else {
      // 有
      const unReadCount = lastMsg.unReadCount + msg.unReadCount;
      if (msg.creatTime > lastMsg.creatTime) {
        lastMsgObjs[chatId] = msg;
      }
      lastMsgObjs[chatId].unReadCount = unReadCount;
    }
  });
  const lastMsgs = Object.values(lastMsgObjs);
  lastMsgs.sort(function (m1, m2) {
    return m2.creatTime - m1.creatTime;
  });
  return lastMsgs;
}

class Message extends Component {
  componentDidMount() {
    this.props.getUser();
  }

  render() {
    const { user } = this.props;
    const { users, chatMsgs } = this.props.chat;

    const lastMsgs = getLastMsgs(chatMsgs, user._id);

    return (
      <List style={{ marginTop: 50, marginBottom: 50 }}>
        {lastMsgs.map((msg) => {
          const targetUserId = msg.to === user._id ? msg.from : msg.to;
          const targetUser = users[targetUserId];
          return (
            <Item
              key={msg._id}
              extra={<Badge text={msg.unReadCount} />}
              arrow="horizontal"
              onClick={() => this.props.history.push(`/chat/${targetUserId}`)}
            >
              <Comment
                author={<a>{targetUser.username}</a>}
                avatar={
                  <Avatar
                    src={
                      targetUser.header
                        ? require(`../../assets/images/${targetUser.header}.png`)
                        : null
                    }
                    alt={targetUser.username}
                  />
                }
                content={<p>{msg.content.length>20?msg.content.substr(0,20)+'...':msg.content}</p>}
              />
            </Item>
          );
        })}
      </List>
    );
  }
}

export default connect((state) => ({ user: state.user, chat: state.chat }), {
  getUser,
})(Message);
